package com.blog.wu.myblog.service;

import com.blog.wu.myblog.base.BaseCrudService;
import com.blog.wu.myblog.dao.UserInfoMapper;
import com.blog.wu.myblog.entity.UserInfo;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @Author wuyanshen
 * @Date 2018-10-10 下午11:05
 * @Discription 用户信息业务类
 */
@Service
public class UserInfoService extends BaseCrudService<UserInfoMapper, UserInfo> {

    /**
     * 用户登录方法
     *
     * @param user
     * @return com.blog.wu.myblog.entity.UserInfo
     * @Date 2018/10/16 下午3:35
     * @Author wuyanshen
     */
    public UserInfo isLogin(UserInfo user) {
        try {
            return super.dao.isLogin(user);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @CacheEvict(allEntries = true)
    @Transactional(readOnly = false,rollbackFor = Exception.class)
    public boolean saveUser(UserInfo userInfo) {
        userInfo.preInsert();
        int flag1 = super.dao.insert(userInfo);
        int flag2 = super.dao.insertUserRole(userInfo);
        if (flag1 > 0 && flag2 > 0) {
            logger.info("新增用户成功");
            return true;
        } else {
            logger.info("新增用户失败");
            return false;
        }
    }

    @CacheEvict(allEntries = true)
    @Transactional(readOnly = false,rollbackFor = Exception.class)
    public boolean deleteUser(UserInfo userInfo) {
        int flag1 = super.dao.delete(userInfo);
        int flag2 = super.dao.deleteUserRole(userInfo);
        if (flag1 > 0 && flag2 > 0) {
            logger.info("删除用户成功");
            return true;
        } else {
            logger.info("删除用户失败");
            return false;
        }
    }

//    @Cacheable
    public List<String> findUserRole(UserInfo userInfo) {
        return super.dao.selectUserRole(userInfo);
    }

    @CacheEvict(allEntries = true)
    @Transactional(readOnly = false,rollbackFor = Exception.class)
    public boolean updateUser(UserInfo userInfo) {
        int flag1 = super.dao.update(userInfo);
        int flag2 = super.dao.deleteUserRole(userInfo);
        int flag3 = 0;
        if (userInfo.getRoles() != null) {
            flag3 = super.dao.insertUserRole(userInfo);
            if (flag1 > 0 && flag3 > 0) {
                logger.info("更新用户成功");
                return true;
            } else {
                logger.info("更新用户失败");
                return false;
            }
        } else {
            if (flag1 > 0 && flag3 == 0) {
                logger.info("更新用户成功");
                return true;
            } else {
                logger.info("更新用户失败");
                return false;
            }
        }

    }


}
